/**
 * Copyright (c) 2018 Ujued and APISP.NET. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cc.witalk.api;

import org.json.JSONObject;

import cc.witalk.BusinessException;
import cc.witalk.domain.User;
import cc.witalk.service.UserService;
import cc.witalk.util.Messages;
import net.apisp.quick.core.annotation.Post;
import net.apisp.quick.core.std.SimpleToken;
import net.apisp.quick.ioc.annotation.Autowired;
import net.apisp.quick.ioc.annotation.Controller;

/**
 * @author Ujued
 * @date 2018-06-26 17:13:52
 */
@Controller
public class AccountAPI {

    @Autowired
    private UserService userService;

    @Post("/login")
    public JSONObject login(JSONObject info) throws BusinessException {
        String username = info.getString("username");
        String passwd = info.getString("password");
        User user = new User();
        user.setUsername(username);
        user.setPasswd(passwd);
        SimpleToken token = userService.login(user);
        JSONObject msg = new JSONObject();
        msg.put("token", token);
        return Messages.ok(msg);
    }

    @Post("/register")
    public JSONObject register(JSONObject info) throws BusinessException {
        User user = new User();
        user.setEmail(info.getString("email"));
        user.setUsername(info.getString("username"));
        user.setPasswd(info.getString("password"));
        try {
            user.setNickname(info.getString("nickname"));
        } catch (Exception e) {
        }
        userService.register(user);
        return Messages.ok(new JSONObject().put("id", user.getId()));
    }
}
